package com.mhc.suzuki.service.impl;

import com.mhc.suzuki.dal.model.CarInfoDO;
import com.mhc.suzuki.dal.query.CarInfoQuery;
import com.mhc.suzuki.manager.CarInfoManager;
import com.mhc.suzuki.service.CarInfoService;
import com.mhc.suzuki.util.BeanCopierUtil;
import com.mhc.suzuki.vo.CarInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class CarInfoServiceImpl implements CarInfoService {

    @Autowired
    private CarInfoManager carInfoManager;

    @Override
    public CarInfoVO getCarInfo(String orderNO) {
        CarInfoQuery carInfoQuery = new CarInfoQuery();
        carInfoQuery.createCriteria().andOrderNoEqualTo(orderNO);
        List<CarInfoDO> carInfoDOList = carInfoManager.selectByQuery(carInfoQuery);
        if (!CollectionUtils.isEmpty(carInfoDOList)) {
            CarInfoDO carInfoDO = carInfoDOList.get(0);
            return BeanCopierUtil.convert(carInfoDO, CarInfoVO.class);
        } else {
            return null;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addOrUpdateCarInfo(CarInfoDO carInfoDO, Long staffId) {
        Boolean result;
        CarInfoQuery query = new CarInfoQuery();
        query.createCriteria().andOrderNoEqualTo(carInfoDO.getOrderNo());
        int count = carInfoManager.countByQuery(query);
        if (count > 0) {
            int updateCount = carInfoManager.updateByQuerySelective(carInfoDO, query);
            if (updateCount > 0) {
                result = Boolean.TRUE;
            } else {
                result = Boolean.FALSE;
            }
        } else {
            carInfoManager.insertSelective(carInfoDO);
            result = Boolean.TRUE;
        }
        return result;
    }
}
